﻿using Sharp.WeShare.Common;
using Sharp.WeShare.MP.EnumKey;
using System.Collections.Generic;
using Newtonsoft.Json;
using Sharp.WeShare.MP.MaterialLib.Entity;

namespace Sharp.WeShare.MP.MaterialLib
{
    public class MaterialApi
    {
        /// <summary>
        /// 上传临时素材
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="filename">服务器文件的物理路径，可用Request.MapPath将虚拟路径 转换为物理路径。也可为网络路径，如：http://XXXX</param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static MediaRes AddTemp(string accessToken, string filename, MaterialType type)
        {
            var url = string.Format("https://api.weixin.qq.com/cgi-bin/media/upload?access_token={0}&type={1}", accessToken, type.ToString());
            var form = new List<FormEntity>();
            form.Add(new FormEntity { IsFile = true, Name = "media", Value = filename });
            return Utils.UploadResult<MediaRes>(url, form);
        }
        /// <summary>
        /// 添加多图文
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="arts"></param>
        /// <param name="istemp">是否是临时素材</param>
        /// <returns></returns>
        public static MediaRes AddNews(string accessToken, Articles arts,bool istemp=false)
        {
            var url = string.Format("https://api.weixin.qq.com/cgi-bin/material/add_news?access_token={0}", accessToken);
            if (istemp)
            {
                url = string.Format("https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token={0}", accessToken);
            }
            return Utils.PostResult<MediaRes>(arts, url);
        }
        /// <summary>
        /// 上传图文内图片，获取url
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="filename">服务器文件的物理路径，可用Request.MapPath将虚拟路径 转换为物理路径。也可为网络路径，如：http://XXXX</param>
        /// <returns></returns>
        public static NewImgUrlRes UploadNewImgUrl(string accessToken, string filename)
        {
            var url = string.Format("https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token={0}", accessToken);
            return Utils.UploadResult<NewImgUrlRes>(url, filename);
        }
        /// <summary>
        /// 上传永久素材
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="filename">文件名</param>
        /// <param name="type">类型</param>
        /// <param name="videoTitle">视频标题，视频素材时有效</param>
        /// <param name="videoDesc">视频描述，视频素材时有效</param>
        /// <returns></returns>
        public static MediaRes Add(string accessToken, string filename, MaterialType type, string videoTitle = "", string videoDesc = "")
        {
            var url = string.Format("https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={0}&type={1}", accessToken, type.ToString());
            var form = new List<FormEntity>();
            form.Add(new FormEntity { IsFile = true, Name = "media", Value = filename });
            if (!string.IsNullOrEmpty(videoTitle))
            {
                form.Add(new FormEntity { IsFile = false, Name = "description", Value = JsonConvert.SerializeObject(new { title = videoTitle, introduction = videoDesc }) });
            }
            return Utils.UploadResult<MediaRes>(url, form);
        }

        /// <summary>
        /// 获取临时素材url
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="mediaId"></param>
        /// <returns></returns>
        public static string GetTempUrl(string accessToken, string mediaId)
        {
            var url =
            "http://api.weixin.qq.com/cgi-bin/media/get?access_token={0}&media_id={1}";
            return string.Format(url, accessToken, mediaId);
        }
        /// <summary>
        /// 获取临时素材的内容
        /// </summary>
        /// <param name="accessToken"></param>
        /// <param name="mediaId">素材的id</param>
        /// <param name="ms">文件流。请求成功后，将响应结果填充到此流中</param>
        /// <returns></returns>
        public static BaseRes GetTempFile(string accessToken, string mediaId, FileStreamInfo ms)
        {
            var url = GetTempUrl(accessToken, mediaId);
            var ret = Utils.DownLoadByPost(url, "", ms);
            if (ret == "")
            {
                return new BaseRes { errcode = 0 };
            }
            return JsonConvert.DeserializeObject<BaseRes>(ret);
        }

        /// <summary>
        /// 获取永久图文素材
        /// </summary>
        /// <param name="accessToken">全局凭证</param>
        /// <param name="mediaId">媒体ID</param>
        public static ArticleRes GetNews(string accessToken, string mediaId)
        {
            var url =
          string.Format("https://api.weixin.qq.com/cgi-bin/material/get_material?access_token={0}", accessToken);
            return Utils.PostResult<ArticleRes>(new { media_id = mediaId }, url);
        }
        /// <summary>
        /// 获取视频素材
        /// </summary>
        /// <param name="mediaId"></param>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public static VideoRes GetVideo(string accessToken,string mediaId)
        {
            var url =
         string.Format("https://api.weixin.qq.com/cgi-bin/material/get_material?access_token={0}", accessToken);
            return Utils.PostResult<VideoRes>(new { media_id = mediaId }, url);
        }
        /// <summary>
        /// 获取除了视频，图文素材之外的其他素材
        /// </summary>
        public static BaseRes Get(string accessToken, string mediaId, FileStreamInfo ms)
        {
            var url =
        string.Format("https://api.weixin.qq.com/cgi-bin/material/get_material?access_token={0}", accessToken);

            var ret = Utils.DownLoadByPost(url, JsonConvert.SerializeObject(new { media_id = mediaId }), ms);
            if (ret == "")
            {
                return new BaseRes { errcode = 0 };
            }
            return JsonConvert.DeserializeObject<BaseRes>(ret);
        }
        /// <summary>
        /// 删除永久素材
        /// </summary>
        /// <param name="mediaId"></param>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public static BaseRes Del(string accessToken,string mediaId)
        {
            var url = "https://api.weixin.qq.com/cgi-bin/material/del_material?access_token={0}";
            return Utils.PostResult<BaseRes>(new { media_id = mediaId },
            string.Format(url, accessToken));
        }
        /// <summary>
        /// 修改永久图文素材
        /// </summary>
        /// <param name="accessToken">调用凭据</param>
        /// <param name="mediaId">图文素材ID</param>
        /// <param name="index">要更新的文章在图文消息中的位置（多图文消息时，此字段才有意
        ///   义），第一篇为0</param>
        /// <param name="article">图文实体。此处表示的是修改后的图文信息</param>
        public static BaseRes UpdateNewItem(string accessToken, string mediaId, int
        index, Article article)
        {
            var url =
            string.Format("https://api.weixin.qq.com/cgi-bin/material/update_news?access_token={0}", accessToken);
            var obj = new
            {
                media_id = mediaId,
                index = index,
                articles = article
            };
            return Utils.PostResult<BaseRes>(obj, url);
        }
        /// <summary>
        /// 获取永久素材总数
        /// </summary>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public static MaterialCount GetCount(string accessToken)
        {
            var url =
            string.Format("https://api.weixin.qq.com/cgi-bin/material/get_materialcount?access_token={0}", accessToken);
            return Utils.GetResult<MaterialCount>(url);
        }
        /// <summary>
        /// 获取永久素材列表，会包含公众号在公众平台官网素材管理模块中新建的图文消息、语音、视
        /// 频等素材（但需要先通过获取素材列表来获知素材的media_id）
        ///临时素材无法通过本接口获取
        /// </summary>
        /// <param name="mediaType">素材类型</param>
        /// <param name="index">从全部素材的指定索引开始返回。
        ///0表示从第一个素材返回</param>
        /// <param name="count">返回素材的数量，取值在1到20之间</param>
        /// <param name="accessToken">全局票据</param>
        public static Materials GetList(string accessToken,MaterialType mediaType, int index, int
        count)
        {
            var url =
            string.Format("https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token={0}", accessToken);
            var obj = new { type = mediaType.ToString(), offset = index, count = count };
            return Utils.PostResult<Materials>(obj, url);
        }


    }
}
